import { useEffect, useRef } from 'react';
import { updateCSS, removeCSS } from 'rc-util/lib/Dom/dynamicCSS';
import Cache from '../utils/Cache'; // 假设 Cache 类在同目录下的 Cache.ts 文件中

const styleCache = new Cache('styleCacheInstance');

const processNestedStyles = (styleObject, parentClassName) => {
  const cssRules = {};

  const generateCSS = (styleObj, parent) => {
    Object.entries(styleObj).forEach(([key, value]) => {
      if (typeof value === 'object') {
        const nestedClassName = `${parent}${key.replace('&', '')}`;
        generateCSS(value, nestedClassName);
      } else {
        const cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
        const selector = `.${parent}`;
        if (!cssRules[selector]) {
          cssRules[selector] = {};
        }
        cssRules[selector][cssKey] = value;
      }
    });
  };

  generateCSS(styleObject, parentClassName);

  return Object.entries(cssRules)
    .map(([selector, styles]) => {
      const styleString = Object.entries(styles)
        .map(([key, value]) => `${key}: ${value};`)
        .join(' ');
      return `${selector} { ${styleString} }`;
    })
    .join(' ');
};

const useStyle = (styleObject, className) => {
  const styleRef = useRef(null);

  useEffect(() => {
    const cacheKey = [className, JSON.stringify(styleObject)];
    const cachedValue = styleCache.get(cacheKey);

    if (cachedValue) {
      styleRef.current = updateCSS(cachedValue[1], className);
    } else {
      const cssString = processNestedStyles(styleObject, className);
      styleRef.current = updateCSS(cssString, className);
      styleCache.update(cacheKey, () => [Date.now(), cssString]);
    }

    return () => {
      if (styleRef.current) {
        removeCSS(className);
      }
    };
  }, [styleObject, className]);

  return className;
};

export default useStyle;
